<?php

/*
	PIE Content Management System
	John Girata
	Licensed under the GNU General Public License version 3
*/

defined('PIESECVAR') or die('Restricted Access');

class com_page
{
	function __construct()
	{
		global $db, $controller, $login;
		
		// Get the page ID from the URL
		$page = (isset($_GET['page'])) ? $db->escape($_GET['page']) : 'home';
		
		// Load that page from the database
		$db->query("SELECT `id`,`title`,`content`,`author`,`updater`,`post_date`,`last_update`,`hide_to_guests`,`groups` FROM `#__pages` WHERE `id`='$page'");
		
		// Error checking
		if($db->get_num_rows() == 0) // i.e., there are no pages with that ID
			$db->query("SELECT * FROM `#__pages` WHERE `id`='e404' LIMIT 1");
		else if($db->get_num_rows() > 1) // i.e., there are multiple pges with that ID
		{
			$db->query("SELECT * FROM `#__pages` WHERE `id`='e500' LIMIT 1");
			$controller->log_error("Multiple entries for page id '$page'", true);
		}
		
		$info = $db->get_array();
		$info = $info[0];
		
		// Check that the user has the necessar permissions
		if($info['hide_to_guests'])
		{
			if(!$login->get_login())
			{
				$db->query("SELECT * FROM `#__pages` WHERE `id`='e403' LIMIT 1");
				$info = $db->get_array();
				$info = $info[0];
			}
			else if(!empty($info['groups']))
			{
				$permitted_groups = $info['groups'];
				$permitted_groups = $permitted_groups[0];
				$permitted_groups = explode(',', $permitted_groups);
				
				$allowed = false;
				$user_groups = $login->get_login();
				$user_groups = $user_groups['groups'];
				
				foreach($permitted_groups as $group)
				{
					if(in_array($group, $user_groups))
						$allowed = true;
				}
					
				if(!$allowed)
				{
					$db->query("SELECT * FROM `#__pages` WHERE `id`='e403' LIMIT 1");
					$info = $db->get_array();
					$info = $info[0];
				}
			}
		}
		
		// Replace the holders in the TMPL file with the values in $info
		$tmpl = file_get_contents(TMPL_DIR . 'com_page/page.tmpl');
		
		$patterns = Array(
			'/<%%ID%%>/',
			'/<%%TITLE%%>/',
			'/<%%CONTENT%%>/',
			'/<%%AUTHOR%%>/',
			'/<%%UPDATER%%>/',
			'/<%%POST_DATE%%>/',
			'/<%%LAST_UPDATE%%>/'
		);
		
		$tmpl = preg_replace($patterns, $info, $tmpl);
		$controller->add_content($tmpl);
		$controller->set_title($info['title']);
	}
}

$page = new com_page();

?>